/*
 * Hidden Equity LLC
 * Author: Maksym Fedyay, Kyiv, mcsimf@gmail.com
 * Date: 29.02.2012
 */

package com.hiddenequity.acts;

import java.util.ArrayList;

import com.hiddenequity.campaign_service.CampaignFormAddSetLogic;
import com.hiddenequity.campaign_targeting_service.CampaignTargetingResponseParser;
import com.hiddenequity.campaign_targeting_service.CampaignTargetingService;
import com.hiddenequity.utils.AuthService;
import com.hiddenequity.utils.Communication;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.View;
import android.view.ViewStub;
import android.widget.CheckBox;
import android.widget.RadioButton;


public class Act_CampaignDeviceTarget extends Act_Super{
	
	private String campaignId;
	private String campaignName;
	
	
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}
	
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.super_operation_layout);
		
		((ViewStub) findViewById(R.id.stub_campaign_device_target)).inflate();
        
        Intent intent = getIntent();
        
        campaignId = intent.getStringExtra("campaignId");
        campaignName = intent.getStringExtra("campaignName");
        
        title.setText(R.string.title_device_set);
        sub_title.setText(campaignName);
        filter.setVisibility(View.GONE);
        
        runOperationAsync(OPERATION_GET_DATA, getString(R.string.progress_loading), false);

    }//onCreate
    
    
    
    /*
     * Set form according to retrieved data
     */
    private void setUpForm(){
    	CheckBox cb_Desktop = (CheckBox) findViewById(R.id.cb_Desktop);
    	CheckBox cb_Mobile = (CheckBox) findViewById(R.id.cb_Mobile);
    	RadioButton rb_AllOS = (RadioButton) findViewById(R.id.rb_AllOS);
    	RadioButton rb_SelectOS = (RadioButton) findViewById(R.id.rb_SelectOS);
    	CheckBox cb_AndriodOS = (CheckBox) findViewById(R.id.cb_AndriodOS);
    	CheckBox cb_iOS = (CheckBox) findViewById(R.id.cb_iOS);
    	CheckBox cb_webOS = (CheckBox) findViewById(R.id.cb_webOS);
    	
    	
    	if(!usedPlatforms.isEmpty()){
    		if(usedPlatforms.get(0).equals("DESKTOP")){
    			cb_Desktop.setChecked(true);
    			cb_Mobile.setChecked(false);

    			rb_AllOS.setEnabled(false);
    			rb_SelectOS.setEnabled(false);
    			
    		} else if(usedPlatforms.get(0).equals("HIGH_END_MOBILE")){
    			cb_Desktop.setChecked(false);
    			cb_Mobile.setChecked(true);
    		}
    	}
    	
    	if(!usedMobile.isEmpty()){
    		rb_AllOS.setChecked(false);
    		rb_SelectOS.setChecked(true);
    		cb_AndriodOS.setEnabled(true);
    		cb_iOS.setEnabled(true);
    		cb_webOS.setEnabled(true);
    		
    		if(usedMobile.contains("Android"))
    			cb_AndriodOS.setChecked(true);
		
    		if(usedMobile.contains("iPhone") || usedMobile.contains("iPad"))
    			cb_iOS.setChecked(true);
    		
    		if(usedMobile.contains("Palm"))
    			cb_webOS.setChecked(true);
    	}
    }//setUpForm
    
    
    
    /*
     * Get campaign device targeting data 
     */
    
    private ArrayList<String> usedPlatforms = new ArrayList<String>();
    private ArrayList<String> usedMobile = new ArrayList<String>();
    
    private void getCampaignDeviceTargeting(){
    	
    	CampaignTargetingResponseParser targetingParser = new CampaignTargetingResponseParser(
    			Communication.postSOAP(
    					CampaignTargetingService.URL_CAMPAIGN_TARGET_SERVICE, 
    					CampaignTargetingService.getCampaignTargetById(campaignId)
    				)
    			);
    	
    	responseErrorString = targetingParser.checkForErrors();

    	usedPlatforms.addAll(targetingParser.getCampaignPlatformTarget());
    	usedMobile.addAll(targetingParser.getCampaignMobileTarget());

    }//getCampaigntargetData
    
 
    
	/*
	 * Asinc data request
	 */
	private void runOperationAsync(final int operation, String message, boolean overlap) {
		// Stop if thread is alive
		if (thread.isAlive() && !overlap)
			return;

		// Show progress dialog
		final ProgressDialog progressDialog = ProgressDialog.show(this, "",
				message, true);

		// Check if Internet connection alive
		if (!isConnectionAvalable()) {
			progressDialog.dismiss();
			return;
		}

		thread = new Thread() {
			public void run() {
				// Perform authentication
				new AuthService(Act_CampaignDeviceTarget.this, getApplication());

				// Perform operation
				if (AuthService.authToken != null) {
					try {
						switch (operation) {
						case OPERATION_GET_DATA:
							Act_CampaignDeviceTarget.this
									.getCampaignDeviceTargeting();
							break;
						case OPERATION_SET_PLATFORM:
							Act_CampaignDeviceTarget.this
									.setCampaignPlatformTargeting();
							break;
						case OPERATION_SET_MOBILE:
							Act_CampaignDeviceTarget.this
									.setCampaignMobileTargeting();

							break;
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

				// Perform postoperation
				Act_CampaignDeviceTarget.this.runOnUiThread(new Runnable() {
					public void run() {

						progressDialog.dismiss();

						if (AuthService.authToken != null) {

							showOperationError(R.string.msg_title_error,
									responseErrorString);

							switch (operation) {
							case OPERATION_GET_DATA:
								Act_CampaignDeviceTarget.this.setUpForm();
								break;
							case OPERATION_SET_PLATFORM:
								runOperationAsync(OPERATION_SET_MOBILE,
										getString(R.string.progress_saving),
										true);
								break;
							case OPERATION_SET_MOBILE:
								Act_CampaignDeviceTarget.this.finish();
								break;
							}

						} else {
							Intent intent = new Intent(
									Act_CampaignDeviceTarget.this.getApplicationContext(),
									Act_Login.class);
							startActivityForResult(intent,
									REQUEST_REFRESH_REQUIRED);
						}
					}
				});
			}
		};
		thread.start();

	}//runOperationAsync
	
	
	
    /*
     * Set campaign platform targeting
     */
    private void setCampaignPlatformTargeting(){
        
        CampaignTargetingResponseParser targetingParser = new CampaignTargetingResponseParser(
        		Communication.postSOAP(
    				CampaignTargetingService.URL_CAMPAIGN_TARGET_SERVICE, 
    				CampaignTargetingService.setPlatformTarget(campaignId, fullPlatform, hiEndMobile)
    				)
        		);
        	
        responseErrorString = targetingParser.checkForErrors();
    }
    


    /*
     * Set campaign mobile platform targeting
     */    
    private void setCampaignMobileTargeting(){

        CampaignTargetingResponseParser targetingParser = new CampaignTargetingResponseParser(
        		Communication.postSOAP(
    				CampaignTargetingService.URL_CAMPAIGN_TARGET_SERVICE, 
    				CampaignTargetingService.setMobilePlatformTarget(campaignId, Android, iPad, iPhone, Palm)
    				)
        		);
        	
        responseErrorString = targetingParser.checkForErrors();
    }//setCampaignMobileTargeting   
 
    
	private boolean fullPlatform;
	private boolean hiEndMobile;
	private boolean Android = false;
	private boolean iPad = false;
	private boolean iPhone = false;
	private boolean Palm = false;
	
  
    /*
     * Button save handler
     */
    public void onClick_saveData(View v){
    	CheckBox cb_Desktop = (CheckBox) findViewById(R.id.cb_Desktop);
    	CheckBox cb_Mobile = (CheckBox) findViewById(R.id.cb_Mobile);
    	RadioButton rb_AllOS = (RadioButton) findViewById(R.id.rb_AllOS);
    	CheckBox cb_AndriodOS = (CheckBox) findViewById(R.id.cb_AndriodOS);
    	CheckBox cb_iOS = (CheckBox) findViewById(R.id.cb_iOS);
    	CheckBox cb_webOS = (CheckBox) findViewById(R.id.cb_webOS);
    	
    	
    	//Set platform info
    	fullPlatform = cb_Desktop.isChecked();
    	hiEndMobile = cb_Mobile.isChecked();

    	//Set mobile info
    	boolean allOS = rb_AllOS.isChecked();
    	
    	if(hiEndMobile)
    		if(!allOS){
    			Android = cb_AndriodOS.isChecked();
    			if(cb_iOS.isChecked()){
    				iPad = true;
    				iPhone = true;
    			}
    			Palm = cb_webOS.isChecked();	
    		}

    	runOperationAsync(OPERATION_SET_PLATFORM, getString(R.string.progress_saving), false);
     	
    }
    
    
    /*
     * Form Logic
     */
    public CampaignFormAddSetLogic logic = new CampaignFormAddSetLogic(this);
    public void setLogic(View v){
    	logic.setLogic(v);
    }//setLogic    
 
}
